package com.lq.ecoldchain.model

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import com.alipay.sdk.app.PayTask
import com.lq.ecoldchain.base.view.App

/*
*2019/1/21 0021  10:07
*function by lq
*/
@SuppressLint("StaticFieldLeak")
class AliPayModel(val activity:Activity){
    private val SDK_PAY_FLAG = 1

    @SuppressLint("HandlerLeak")
    private val mHandler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                SDK_PAY_FLAG -> {
                    val payResult = PayResult(msg.obj as Map<String, String>)
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    val resultInfo = payResult.getResult()// 同步返回需要验证的信息
                    val resultStatus = payResult.getResultStatus()

                    Log.e("PayModel", "msg.obj.toString():" + msg.obj.toString())
                    Log.e("PayModel", "resultInfo:$resultInfo")
                    // 判断resultStatus 为9000则代表支付成功
                    // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                    Toast.makeText(App.instance, if (TextUtils.equals(resultStatus, "9000")) "支付成功" else "支付失败", Toast.LENGTH_SHORT).show()
                }
            }
        }

    }

    /**
     * 支付宝支付业务
     */
    fun payV2(orderInfo: String) {
        val payRunnable = Runnable {
            val alipay = PayTask(activity)
            val result = alipay.payV2(orderInfo, true)
            Log.e("msp", result.toString())
            val msg = Message()
            msg.what = SDK_PAY_FLAG
            msg.obj = result
            mHandler.sendMessage(msg)
        }

        val payThread = Thread(payRunnable)
        payThread.start()
    }
}